package com.foreknow.dao.impl;

import com.foreknow.dao.UserDao;
import com.foreknow.po.User;
import com.foreknow.util.CommonUtil;
import com.foreknow.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private Connection conn = null;
    private PreparedStatement pst = null;

    @Override
    public User getUserByIdByPass(String userId, String password) throws SQLException {
        String sql = "select * from user where userId = ? and password = ?";
        User user = new User();
        try{
            conn = DBUtil.getConnection();
            pst = conn.prepareStatement(sql);
            pst.setString(1,userId);
            pst.setString(2,password);
            ResultSet rs = pst.executeQuery();
            while (rs.next()){
                user.setUserId(rs.getString("userId"));
                user.setPassword(rs.getString("password"));
                user.setUserName(rs.getString("userName"));
                user.setUserSex(rs.getInt("userSex"));
                user.setUserImg(rs.getString("userImg"));
                user.setDelTag(rs.getInt("delTag"));
            }
        }finally {
            DBUtil.close(pst);
        }
        return user;
    }

    @Override
    public Integer getUserById(String userId) throws SQLException {
        String sql = "select count(*) as count from user where userId = ?";
        int result = 0;
        try{
            conn = DBUtil.getConnection();
            pst = conn.prepareStatement(sql);
            pst.setString(1,userId);
            ResultSet rs = pst.executeQuery();
            while (rs.next()){
                result = rs.getInt("count");
            }
        }finally {
            DBUtil.close(pst);
        }

        return result;
    }

    @Override
    public Integer saveUser(String userId, String password, String userName, int userSex) throws SQLException {
        String sql = "insert into user(userId,password,userName,userSex) values (?,?,?,?)";
        int result = 0;
        try{
            conn = DBUtil.getConnection();
            pst = conn.prepareStatement(sql);
            pst.setString(1,userId);
            pst.setString(2,password);
            pst.setString(3,userName);
            pst.setInt(4,userSex);
            result = pst.executeUpdate();
        }finally {
            DBUtil.close(pst);
        }
        return result;
    }


    public static void main(String[] args) {
//        UserDao userDao = new UserDaoImpl();
//        try {
////            int r =userDao.getUserById("11111111111");
////            System.out.println(r);
////            int r = userDao.saveUser("3216548","654321","GLG",1);
////            System.out.println(r);
//        } catch (SQLException throwables) {
//            throwables.printStackTrace();
//        }
        System.out.println(CommonUtil.getCurrentDate());

    }
}
